package com.elvish.efast.modules.sys.controller;

import com.elvish.efast.common.anno.BuildTree;
import com.elvish.efast.common.consts.Const;
import com.elvish.efast.common.entity.Result;
import com.elvish.efast.common.entity.TreeData;
import com.elvish.efast.common.enums.ResultCode;
import com.elvish.efast.common.utils.CommonUtil;
import com.elvish.efast.common.utils.ResultUtil;
import com.elvish.efast.modules.sys.entity.Menu;
import com.elvish.efast.modules.sys.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * (TMenu)表控制层
 *
 * @author makejava
 * @since 2018-11-02 11:39:36
 */
@RestController
@RequestMapping("/menu")
@Slf4j
public class MenuController {

    /**
     * 服务对象
     */
    @Autowired
    private MenuService tMenuService;

    /**
     * 查询菜单列表
     *
     * @return 响应消息
     */
    @GetMapping("/queryAll")
    public Result queryAll(Menu menu) {
        return ResultUtil.success(tMenuService.queryAll(menu));
    }

    /**
     * 查询菜单列表
     *
     * @param page  起始条数
     * @param limit 每页条数
     * @return 响应消息
     */
    @GetMapping("/queryAllByLimit")
    public Result queryAllByLimit(int page, int limit) {
        return ResultUtil.success(tMenuService.queryAllByLimit(page, limit));
    }

    /**
     * 查询所有菜单
     *
     * @return 所有菜单数据
     */
    @GetMapping("/getTreeData")
    @BuildTree
    public List<TreeData> getTreeData() {
        return tMenuService.getTreeData();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public Menu selectOne(String id) {
        return this.tMenuService.queryById(id);
    }


    /**
     * 操作菜单
     *
     * @param oper 操作符
     * @param menu 菜单对象
     * @return 响应消息
     */
    @PostMapping("/editMenu")
    public Result editMenu(int oper, @RequestBody Menu menu) {
        Result result = null;
        try {
            if (oper == Const.OperationType.ADD) {
                menu.setId(CommonUtil.uuid());
                this.tMenuService.insert(menu);
            } else if (oper == Const.OperationType.UPDATE) {
                this.tMenuService.update(menu);
            } else if (oper == Const.OperationType.DELETE) {
                this.tMenuService.deleteById(menu);
            }
            result = ResultUtil.success();
        } catch (Exception e) {
            log.error("editMenu error", e);
            result = ResultUtil.fail(ResultCode.ERROR);
        }
        return result;
    }
}